#pragma once

#include <Common/Common.h>
#include "WebSocketProxy.h"
#include "WebSocketClientEvent.h"
using namespace std;

struct IWebSocketConnectorCallback
{
    virtual IWebSocketHandler* OnWebSocketConnected(CWebSocketProxyPtr spProxy) = 0;
    virtual void OnWebSocketConnectError(Int32 nError) = 0;
};

class CWebSocketConnector : public ITCPConnector2Callback, public IClientHandshakeCallback, public IMessageDispatcher
{
public:
    CWebSocketConnector(CEventEngine *pEngine);
    virtual ~CWebSocketConnector();

public:
    Bool Connect(const string &strUrl, Int32 nTimeout, IWebSocketConnectorCallback *pCallback);

protected:
    virtual void OnConnected();
    virtual void OnConnectFailed(Int32 nError);
    virtual void OnConnectTimeout();

    //IClientHandshakeCallback
    virtual IWebSocketHandler* OnHandshakeCompleted(CWebSocketProxyPtr spProxy);
    virtual void OnHandshakeFailed();

    virtual void DispatchMessage(CClientEvent *pClientEvent, void *pMsg);

private:
    Bool ParseUrl(const string& strMsg);
    string MakeHandshakeMsg();

protected:
    CEventEngine*                               m_pEngine;

    IWebSocketConnectorCallback*                m_pConnectorCallback;
    CWebSocketClientEvent*                      m_pClientEvent;

    CTCPConnector2                              m_connector;
    CSocketAddr                                 m_addr;;
    string                                      m_uri;
};
